/**
 * 订单核心数据概览
 * @author hanzhichen (hanzhichen@baijia.com)
 * @date 2021-03-02
 */

import {useState, useEffect, useMemo} from 'react';
import {usePersistFn, useRequest} from 'ahooks';
import {Card} from 'antd';
import {querySelectOptions} from '~/service/refundReport';
import {INPUT_TYPE_ENUM} from '~/component/SearchForm/dateRanges';
import {fetchReports, getReportInfo} from '~/service/reports';
import SearchForm from '../../common/CommonSearchBar';
import {
    convertSearcherParams,
    formatRangePickerValue,
    addDashBoardIdToDimensionAndValues
} from '../../common/utils';
import {generateColumns} from '../utils/indicator';
import CollectListView from './CollectListView';
import {searchFormCfg, selectUnitId} from './config';

// 设置默认时间
const initValues = {};
const formItemLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16}
};
const tailLayout = {
    wrapperCol: {span: 24}
};
const formatDateSearchValueToDate = formatRangePickerValue('YYYYMMDD');

/** 把searchFormValue转换成查询接口参数的permissions */
const convertParamsToPermissions = (params, reportDimension, searchFormCfg) => {
    const paramList = convertSearcherParams(params);
    // 添加label
    paramList.forEach(item => {
        const cfg = searchFormCfg.find(item1 => item1.key === item.dimensionId);
        item.beDimensionName = cfg.dimensionName;
    });
    const permissions = paramList?.map(aParam => {
        const rdItem = reportDimension?.find(ele => ele.dimensionName === aParam.beDimensionName) ?? {};
        const dimensionId = rdItem?.dimensionId;
        if (aParam?.dimensionId === 'begin_date') {
            const filterItems = Array.isArray(aParam?.value)
                ? aParam?.value.map(vItem => vItem.format('YYYYMMDD'))
                : [];
            return {
                dimensionId,
                filterItems
            };
        }
        return {
            dimensionId,
            filterItems: Array.isArray(aParam?.value)
                ? aParam.value
                : aParam.value == null
                    ? []
                    : [aParam.value]
        };
    }) ?? [];
    return permissions;
};

/** 拼接数据查询参数 /api/portal/search */
const getQueryParams = (id, permissions) => ({
    id,
    permissions
});

const Part2 = props => {
    const {id3} = props;

    // 维度的id, 需要查询
    const [reportDimension3, setReportDimension3] = useState([]);
    useEffect(() => {
        // query detail
        id3 && getReportInfo({id: id3})
            .then(res => {
                const reportDimension = res?.data?.reportDimension ?? [];
                setReportDimension3(reportDimension);
            })
            .catch(error => {
                if (error) {
                    console.log(error, 'error');
                }
            });
    }, [id3]);

    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValue, setSearchFormValues] = useState(initValues);

    // 查询参数, 缓存起来给下载用?
    const [queryParams3, setQueryParams3] = useState([]);

    // chart查询方法
    const {
        data: data3,
        loading: loading3,
        run: run3,
        refresh: refresh3
    } = useRequest(fetchReports, {
        manual: true,
        formatResult(res) {
            return res?.data;
        }
    });

    // 之所以抽离出来, 是为了点击重置时, 能直接重置界面
    const [tableData, setTableData] = useState({});
    const {columns = [], dataSource = []} = tableData || {};

    useEffect(() => {
        setTableData(data3);
    }, [data3]);

    const tableColumns = useMemo(() => {
        const newTableColumns = generateColumns(
            columns,
            INPUT_TYPE_ENUM.SINGLE_DAY
        );
        // 添加tooltip

        return newTableColumns;
    }, [columns]);

    /** 点击搜索按钮 */
    const handleSearch = params => {
        // 换成当前表单数据
        setSearchFormValues(params);
        // 获取查询参数
        const queryParams3 = getQueryParams(
            id3,
            convertParamsToPermissions(params, reportDimension3, searchFormCfg)
        );
        // 缓存查询参数
        setQueryParams3(queryParams3);
        // 查询
        run3(queryParams3);
    };

    /** 点击重置按钮 */
    const handleReset = () => {
        // 换成当前表单数据
        setSearchFormValues(initValues);
        // 清空表格数据
        setTableData({});
    };

    // 请求单个表单配置项
    const handleFetchOptions = usePersistFn(
        ({
            key,
            searchKey,
            pager,
            dependItemKey,
            dependItemValue,
            isGetingMore,
            options: curOptions,
            fieldsValue
        }) => {
            const permissions = searchFormCfg
                ?.map(item => {
                    if (item.key === 'begin_date') {
                        const filterItems = fieldsValue[item.key]
                            ? [fieldsValue[item.key]?.format('YYYYMMDD'), fieldsValue[item.key]?.format('YYYYMMDD')]
                            : [];
                        return {
                            dimensionId: `${selectUnitId}_${item.key}`,
                            dimensionName: item.key,
                            filterItems,
                        };
                    }
                    return {
                        dimensionId: `${selectUnitId}_${item.key}`,
                        dimensionName: item.key,
                        filterItems: Array.isArray(fieldsValue[item.key])
                            ? fieldsValue[item.key]
                            : fieldsValue[item.key] == null
                                ? []
                                : [fieldsValue[item.key]]
                    };
                })
                ?.filter(item => item.filterItems?.length);

            const params = {
                pager,
                dimensionId: `${selectUnitId}_${key}`,
                dimensionName: key,
                searchKey,
                permissions,
                unitId: selectUnitId
            };

            querySelectOptions(params).then(res => {
                const {data, pager} = res;
                let options =
                    data.map(item => ({
                        key: item,
                        value: item,
                        label: item
                    })) || [];
                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }
                setSelectOptions({key, options, pager});
            });
        }
    );

    return (
        <Card title="课节数据汇总">
            <SearchForm
                noCache
                formItemLayout={formItemLayout}
                tailLayout={tailLayout}
                labelAlign="left"
                loading={loading3}
                config={searchFormCfg}
                initialValues={initValues}
                selectOptions={selectOptions}
                onOk={handleSearch}
                onReset={handleReset}
                onfetchOptions={handleFetchOptions}
            />
            {id3 && (
                <CollectListView
                    isloading={loading3}
                    queryParams={queryParams3}
                    columns={tableColumns}
                    dataSource={dataSource}
                />
            )}
        </Card>
    );
};

export default Part2;
